package org.erp.common.manager;

import lombok.AllArgsConstructor;
import org.erp.common.context.StockLockContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
@AllArgsConstructor
public class StockBatchLockManager {

    private final StringRedisTemplate redis;

    public void partialUnlockIfNecessary(String busyKey) {

        String batchKey = StockLockContext.getBatchKey();
        if (batchKey == null) return;


        boolean hasExternal = StockLockContext.hasExternal();
        List<String> internalIds = StockLockContext.getInternalIds();

        // 无外部 IDs = 一次性释放所有
        if (!hasExternal) {
            releaseAll(batchKey, busyKey);
            return;
        }

        // 有外部 IDs = 只释放内部
        if (internalIds != null && !internalIds.isEmpty()) {
            partialRelease(batchKey, busyKey, internalIds);
        }
    }


    /**
     * 只释放部分 id（内部逻辑）
     */
    public void partialRelease(
            String batchKey,
            String busyKey,
            List<String> ids) {

        // 清 busy 集合
        redis.opsForSet().remove(busyKey, ids.toArray());

        // 更新 batchKey：只保留外部
        String old = redis.opsForValue().get(batchKey);
        if (old == null) return;

        List<String> remain = Arrays.stream(old.split(","))
                .filter(id -> !ids.contains(id))
                .toList();

        if (remain.isEmpty()) {
            redis.delete(batchKey);
        } else {
            redis.opsForValue().set(batchKey, String.join(",", remain));
        }
    }


    /**
     * 全部释放（无外部情况）
     */
    public void releaseAll(
            String batchKey,
            String busyKey) {

        String ids = redis.opsForValue().get(batchKey);
        if (ids == null) return;

        List<String> idList = Arrays.asList(ids.split(","));

        redis.opsForSet().remove(busyKey, idList.toArray());
        redis.delete(batchKey);
    }
}
